<template>
  <div class="activity-list">
    <!-- 调试信息 (临时) -->
    <div v-if="showDebugInfo" class="debug-info" style="background: #f0f9ff; padding: 10px; margin-bottom: 20px; border-left: 4px solid #3b82f6;">
      <h4>调试信息</h4>
      <p><strong>NODE_ENV:</strong> {{ nodeEnv }}</p>
      <p><strong>VUE_APP_UPLOAD_API_URL:</strong> {{ uploadApiUrl }}</p>
      <p><strong>Upload Action:</strong> {{ uploadAction }}</p>
      <el-button @click="showDebugInfo = false" size="small" type="primary">隐藏调试信息</el-button>
    </div>
    
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>活动管理</h2>
      <el-button type="primary" @click="openAddDialog">
        <el-icon><Plus /></el-icon>
        新增活动
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="活动标题">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入活动标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="开放中" value="open" />
            <el-option label="已关闭" value="closed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>

        <el-form-item label="场馆">
          <el-select v-model="searchForm.venue_id" placeholder="请选择场馆" clearable style="width: 200px">
            <el-option
              v-for="venue in venueList"
              :key="venue.id"
              :label="venue.name"
              :value="venue.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="开始日期">
          <el-date-picker
            v-model="searchForm.start_date"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="结束日期">
          <el-date-picker
            v-model="searchForm.end_date"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            创建活动
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <el-card shadow="never" class="table-card">
      <div style="overflow-x: auto;">
        <el-table
          :data="activityList"
          v-loading="loading"
          border
          stripe
          style="min-width: 1200px; width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column prop="id" label="活动ID" min-width="80" align="center" />
          <el-table-column prop="title" label="活动标题" min-width="180" />
          <el-table-column prop="organizer.nickname" label="组织者" min-width="120" />
          <el-table-column prop="venue_name" label="场馆" min-width="120" />
          <el-table-column label="时间" min-width="200">
            <template #default="{ row }">
              <div class="time-info">
                <p><strong>开始:</strong> {{ formatDateTime(row.start_time) }}</p>
                <p><strong>结束:</strong> {{ formatDateTime(row.end_time) }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="参与情况" min-width="150" align="center">
            <template #default="{ row }">
              <div class="participant-info">
                <el-tag type="info">{{ row.participant_count || 0 }}/{{ row.max_participants }}</el-tag>
                <el-progress
                  :percentage="getParticipantPercentage(row)"
                  :stroke-width="6"
                  :show-text="false"
                  style="margin-top: 5px"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" min-width="130" align="center">
            <template #default="{ row }">
              <div class="order-status">
                <el-tag v-if="row.orderInfo?.has_order" :type="getOrderStatusType(row.orderInfo.order.status)">
                  {{ row.orderInfo.order.status_text }}
                </el-tag>
                <el-tag v-else type="info">无订单</el-tag>
                <div v-if="row.orderInfo?.has_order" class="order-amount">
                  ¥{{ row.orderInfo.order.amount }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" min-width="150">
            <template #default="{ row }">
              {{ formatDateTime(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="240" fixed="right" align="center">
            <template #default="{ row }">
              <el-button link type="primary" @click="viewDetail(row)">详情</el-button>
              <el-button link type="warning" @click="editActivity(row)">编辑</el-button>
              <el-button 
                v-if="row.orderInfo?.has_order" 
                link 
                type="success" 
                @click="viewOrder(row)"
              >
                查看订单
              </el-button>
              <el-button 
                v-else 
                link 
                type="success" 
                @click="generateOrder(row)"
              >
                生成订单
              </el-button>
              <el-button link type="danger" @click="deleteActivity(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑活动对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑活动' : '创建活动'"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" />
        </el-form-item>

        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入活动描述"
          />
        </el-form-item>

        <el-form-item label="活动图片">
          <el-upload
            class="activity-image-upload"
            :action="uploadAction"
            :headers="uploadHeaders"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :on-success="handleImageSuccess"
            :on-error="handleImageError"
          >
            <img v-if="form.imageUrl" :src="getFullImageUrl(form.imageUrl)" class="uploaded-image" />
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
            <div v-if="!form.imageUrl" class="upload-text">
              <div>点击上传活动图片</div>
              <div class="upload-tip">支持 JPG、PNG 格式，建议尺寸 800x600</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="组织者" prop="organizer_id">
          <el-select v-model="form.organizer_id" placeholder="请选择组织者" filterable style="width: 100%">
            <el-option
              v-for="user in organizerList"
              :key="user.id"
              :label="`${user.nickname}${user.phone ? ` (${user.phone})` : ''}`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="活动场馆">
          <el-select 
            v-model="form.venue_id" 
            placeholder="请选择场馆" 
            clearable 
            :disabled="!!(route.params.venue_id || route.query.venue_id)"
            style="width: 100%"
            @change="handleVenueChange"
          >
            <el-option
              v-for="venue in venueList"
              :key="venue.id"
              :label="`${venue.name} ${venue.max_capacity ? `(容量: ${venue.max_capacity}人)` : ''}`"
              :value="venue.id"
            />
          </el-select>
          <div v-if="route.params.venue_id || route.query.venue_id" class="venue-tip">
            <el-text type="info" size="small">场馆已从列表页面选择，不可修改</el-text>
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="start_time">
              <el-date-picker
                v-model="form.start_time"
                type="datetime"
                placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                @change="handleTimeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="end_time">
              <el-date-picker
                v-model="form.end_time"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                @change="handleTimeChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <div v-if="form.venue_id">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="场馆开始时间" prop="venue_start_time">
                <el-date-picker
                  v-model="form.venue_start_time"
                  type="datetime"
                  placeholder="选择场馆预订开始时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  @change="checkVenueAvailability"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="场馆结束时间" prop="venue_end_time">
                <el-date-picker
                  v-model="form.venue_end_time"
                  type="datetime"
                  placeholder="选择场馆预订结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  @change="checkVenueAvailability"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-alert
            v-if="venueAvailabilityMessage"
            :title="venueAvailabilityMessage"
            :type="venueAvailable ? 'success' : 'error'"
            show-icon
            :closable="false"
            style="margin-bottom: 20px"
          />
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最大人数" prop="max_participants">
              <el-input-number
                v-model="form.max_participants"
                :min="1"
                :max="currentVenueCapacity || 1000"
                style="width: 100%"
              />
              <div v-if="currentVenueCapacity" class="capacity-tip">
                场馆最大容量：{{ currentVenueCapacity }}人
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动状态" prop="status">
              <el-select v-model="form.status" style="width: 100%">
                <el-option label="开放中" value="open" />
                <el-option label="已关闭" value="closed" />
                <el-option label="已取消" value="cancelled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, View as ViewIcon } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/common'
import { uploadApi } from '@/api/upload'
import { venueApi } from '@/api/venue'
import { generateOrderForActivity } from '@/api/order'
import { useUserStore } from '@/stores/user'

export default {
  name: 'ActivityList',
  components: {
    Plus, Search, Refresh, Edit, Delete, ViewIcon
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const userStore = useUserStore()
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const selectedActivities = ref([])
    const venueAvailable = ref(true)
    const venueAvailabilityMessage = ref('')
    const currentVenueCapacity = ref(null)
    const showDebugInfo = ref(true)

    // 环境变量相关 (用于调试)
    const nodeEnv = computed(() => process.env.NODE_ENV || '未设置')
    const uploadApiUrl = computed(() => process.env.VUE_APP_UPLOAD_API_URL || '未设置')

    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      status: '',
      venue_id: '',
      start_date: '',
      end_date: ''
    })

    // 分页
    const pagination = reactive({
      page: 1,
      per_page: 10,
      total: 0,
      pages: 0
    })

    // 数据列表
    const activityList = ref([])
    const venueList = ref([])
    const userList = ref([])

    // 组织者列表（当前管理员+最多9个其他用户）
    const organizerList = computed(() => {
      const currentUser = userStore.userInfo
      // 过滤掉无效用户（没有nickname的用户）
      const validOtherUsers = userList.value.filter(user => 
        user && user.id !== currentUser?.id && user.nickname
      ).slice(0, 9)
      
      // 确保当前用户也有有效的nickname
      const validCurrentUser = currentUser && currentUser.nickname ? currentUser : null
      
      return validCurrentUser ? [validCurrentUser, ...validOtherUsers] : validOtherUsers.slice(0, 10)
    })

    // 上传相关
    const uploadAction = computed(() => {
      // 统一使用新的生产环境URL
      const baseUrl = 'https://dpcurdgwzmkg.sealosbja.site'
      return `${baseUrl}/api/v1/upload/image`
    })
    
    const uploadHeaders = computed(() => {
      return {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    // 表单数据
    const form = reactive({
      id: null,
      title: '',
      description: '',
      organizer_id: '',
      venue_id: '',
      start_time: '',
      end_time: '',
      venue_start_time: '',
      venue_end_time: '',
      max_participants: 20,
      status: 'open',
      imageUrl: '',
      images: []
    })

    // 表单验证规则
    const rules = {
      title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
      organizer_id: [{ required: true, message: '请选择组织者', trigger: 'change' }],
      start_time: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
      end_time: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
    }

    const formRef = ref(null)

    // 获取活动列表
    const fetchActivityList = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page,
          per_page: pagination.per_page,
          ...searchForm
        }
        
        const response = await request.get('/v1/admin/activities', { params })
        
        if (response.code === 200) {
          activityList.value = response.data.activities || []
          pagination.total = response.data.total || 0
          pagination.pages = response.data.pages || 0
          
          // 为每个活动获取订单信息
          await fetchOrderInfoForActivities()
        } else {
          ElMessage.error(response.message || '获取活动列表失败')
        }
      } catch (error) {
        console.error('获取活动列表失败:', error)
        ElMessage.error('获取活动列表失败')
      } finally {
        loading.value = false
      }
    }

    // 为活动列表获取订单信息
    const fetchOrderInfoForActivities = async () => {
      try {
        // 并行获取所有活动的订单信息
        const orderInfoPromises = activityList.value.map(async (activity) => {
          try {
            const response = await request.get(`/v1/admin/activities/${activity.id}/order`)
            if (response.code === 200) {
              activity.orderInfo = response.data
            }
          } catch (error) {
            console.warn(`获取活动${activity.id}订单信息失败:`, error)
            activity.orderInfo = { has_order: false }
          }
          return activity
        })
        
        // 等待所有请求完成
        await Promise.all(orderInfoPromises)
      } catch (error) {
        console.error('批量获取订单信息失败:', error)
      }
    }

    // 获取场馆列表
    const fetchVenueList = async () => {
      try {
        const response = await venueApi.getList({ per_page: 100 })
        if (response.code === 200) {
          venueList.value = response.data.venues || []
        }
      } catch (error) {
        console.error('获取场馆列表失败:', error)
      }
    }

    // 获取用户列表
    const fetchUserList = async () => {
      try {
        const response = await request.get('/v1/admin/users', {
          params: { per_page: 100 }
        })
        if (response.code === 200) {
          userList.value = response.data.users || []
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.page = 1
      fetchActivityList()
    }

    // 重置搜索
    const handleReset = () => {
      Object.assign(searchForm, {
        keyword: '',
        status: '',
        venue_id: '',
        start_date: '',
        end_date: ''
      })
      pagination.page = 1
      fetchActivityList()
    }

    // 显示创建对话框
    const showCreateDialog = () => {
      isEdit.value = false
      
      // 检查路由参数中是否有场馆ID
      const venueIdFromRoute = route.params.venue_id || route.query.venue_id
      
      Object.assign(form, {
        id: null,
        title: '',
        description: '',
        organizer_id: userStore.userInfo?.id || '', // 默认为当前管理员
        venue_id: venueIdFromRoute ? parseInt(venueIdFromRoute) : '',
        start_time: '',
        end_time: '',
        venue_start_time: '',
        venue_end_time: '',
        max_participants: 20,
        status: 'open',
        imageUrl: '',
        images: []
      })
      
      venueAvailabilityMessage.value = ''
      currentVenueCapacity.value = null
      
      // 如果从路由获取到场馆ID，设置场馆容量
      if (venueIdFromRoute) {
        const venueId = parseInt(venueIdFromRoute)
        handleVenueChange(venueId)
      }
      
      dialogVisible.value = true
    }

    // 处理场馆变化
    const handleVenueChange = (venueId) => {
      if (venueId) {
        const venue = venueList.value.find(v => v.id === venueId)
        if (venue) {
          currentVenueCapacity.value = venue.max_capacity
          // 如果当前最大人数超过场馆容量，调整为场馆容量
          if (venue.max_capacity && form.max_participants > venue.max_capacity) {
            form.max_participants = venue.max_capacity
          }
        }
      } else {
        currentVenueCapacity.value = null
      }
      // 清空场馆时间和可用性信息
      form.venue_start_time = ''
      form.venue_end_time = ''
      venueAvailabilityMessage.value = ''
    }

    // 处理时间变化
    const handleTimeChange = () => {
      // 如果活动时间发生变化，同步更新场馆使用时间
      if (form.start_time && form.end_time && form.venue_id) {
        if (!form.venue_start_time) {
          form.venue_start_time = form.start_time
        }
        if (!form.venue_end_time) {
          form.venue_end_time = form.end_time
        }
        checkVenueAvailability()
      }
    }

    // 检查场馆可用性
    const checkVenueAvailability = async () => {
      if (!form.venue_id || !form.venue_start_time || !form.venue_end_time) {
        venueAvailabilityMessage.value = ''
        return
      }

      try {
        const response = await venueApi.checkAvailability(
          form.venue_id,
          form.venue_start_time,
          form.venue_end_time
        )
        
        if (response.code === 200) {
          venueAvailable.value = response.data.available
          
          if (response.data.available) {
            venueAvailabilityMessage.value = '场馆在此时间段可用'
          } else {
            const conflicts = response.data.conflicting_activities
            if (conflicts.length > 0) {
              venueAvailabilityMessage.value = `场馆被以下活动占用：${conflicts.map(a => a.title).join('、')}`
            } else {
              venueAvailabilityMessage.value = '场馆在此时间段不可用'
            }
          }
        }
      } catch (error) {
        console.error('检查场馆可用性失败:', error)
        venueAvailabilityMessage.value = '检查场馆可用性失败'
        venueAvailable.value = false
      }
    }

    // 图片上传前检查
    const beforeImageUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        ElMessage.error('只能上传图片文件！')
        return false
      }
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过 5MB！')
        return false
      }
      return true
    }

    // 图片上传成功
    const handleImageSuccess = (response) => {
      if (response.code === 200) {
        form.imageUrl = response.data.url
        form.images = [response.data.url]
        ElMessage.success('图片上传成功')
      } else {
        ElMessage.error(response.message || '图片上传失败')
      }
    }

    // 图片上传失败
    const handleImageError = () => {
      ElMessage.error('图片上传失败')
    }

    // 编辑活动
    const editActivity = (activity) => {
      isEdit.value = true
      Object.assign(form, {
        id: activity.id,
        title: activity.title,
        description: activity.description,
        organizer_id: activity.organizer_id,
        venue_id: activity.venue_id,
        start_time: activity.start_time,
        end_time: activity.end_time,
        venue_start_time: activity.venue_start_time,
        venue_end_time: activity.venue_end_time,
        max_participants: activity.max_participants,
        status: activity.status,
        imageUrl: activity.images && activity.images.length > 0 ? activity.images[0] : '',
        images: activity.images || []
      })
      
      // 设置场馆容量
      if (activity.venue_id) {
        handleVenueChange(activity.venue_id)
      }
      
      dialogVisible.value = true
    }

    // 提交表单
    const handleSubmit = () => {
      formRef.value?.validate(async (valid) => {
        if (!valid) return

        if (!venueAvailable.value && form.venue_id && form.venue_start_time && form.venue_end_time) {
          ElMessage.error('选择的场馆时间段不可用，请重新选择')
          return
        }

        submitLoading.value = true
        try {
          const data = { 
            ...form,
            images: form.images.length > 0 ? form.images : undefined
          }
          delete data.id
          delete data.imageUrl

          let response
          if (isEdit.value) {
            // 编辑活动
            response = await request.put(`/v1/admin/activities/${form.id}`, data)
          } else {
            // 新增活动
            response = await request.post('/v1/admin/activities', data)
          }
          
          if (response.code === 200) {
            ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
            dialogVisible.value = false
            fetchActivityList()
          } else {
            ElMessage.error(response.message || '操作失败')
          }
        } catch (error) {
          console.error('提交活动失败:', error)
          ElMessage.error('操作失败')
        } finally {
          submitLoading.value = false
        }
      })
    }

    // 生成订单
    const generateOrder = async (activity) => {
      try {
        await ElMessageBox.confirm(
          `确定要为活动"${activity.title}"生成订单吗？`,
          '确认生成订单',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }
        )
        
        const response = await generateOrderForActivity(activity.id, {
          activity_id: activity.id
        })
        
        if (response.code === 200) {
          ElMessage.success('订单生成成功')
          // 重新获取活动列表以更新订单状态
          fetchActivityList()
        } else {
          ElMessage.error(response.message || '订单生成失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('生成订单失败:', error)
          ElMessage.error('生成订单失败')
        }
      }
    }

    // 查看订单
    const viewOrder = (activity) => {
      if (activity.orderInfo?.has_order) {
        const order = activity.orderInfo.order
        ElMessageBox.alert(
          `<div style="text-align: left;">
            <p><strong>订单号：</strong>${order.order_no}</p>
            <p><strong>金额：</strong>¥${order.amount}</p>
            <p><strong>状态：</strong>${order.status_text}</p>
            <p><strong>创建时间：</strong>${order.created_at}</p>
            <p><strong>活动：</strong>${activity.title}</p>
            <p><strong>场馆：</strong>${activity.orderInfo.activity.venue_name}</p>
            ${order.payment_required ? '<p style="color: #e6a23c;"><strong>⚠️ 待支付</strong></p>' : ''}
          </div>`,
          '订单详情',
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '关闭'
          }
        )
      }
    }

    // 获取订单状态类型
    const getOrderStatusType = (status) => {
      const statusMap = {
        0: 'warning',  // 未支付
        1: 'success',  // 已支付
        2: 'info',     // 已取消
        3: 'success',  // 已完成
        4: 'danger'    // 已退款
      }
      return statusMap[status] || 'info'
    }

    // 删除活动
    const deleteActivity = async (activity) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除活动"${activity.title}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await request.delete(`/v1/admin/activities/${activity.id}`)
        ElMessage.success('删除成功')
        fetchActivityList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除活动失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 查看详情
    const viewDetail = (activity) => {
      // 跳转到详情页面
      router.push(`/activity/detail/${activity.id}`)
    }

    // 处理选择变化
    const handleSelectionChange = (selection) => {
      selectedActivities.value = selection
    }

    // 分页变化
    const handleSizeChange = (val) => {
      pagination.per_page = val
      pagination.page = 1
      fetchActivityList()
    }

    const handleCurrentChange = (val) => {
      pagination.page = val
      fetchActivityList()
    }

    // 关闭对话框
    const handleDialogClose = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }

    // 工具函数
    const getStatusType = (status) => {
      const statusMap = {
        'open': 'success',
        'closed': 'info',
        'cancelled': 'danger'
      }
      return statusMap[status] || 'info'
    }

    const getStatusText = (status) => {
      const statusMap = {
        'open': '开放中',
        'closed': '已关闭',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知'
    }

    const getParticipantPercentage = (activity) => {
      if (!activity.max_participants) return 0
      return Math.min(Math.round((activity.participant_count || 0) / activity.max_participants * 100), 100)
    }

    function getFullImageUrl(url) {
      if (!url) return '';
      if (/^https?:\/\//.test(url)) return url;
      if (url.startsWith('/uploads/')) return imageBaseUrl.value + url;
      return `${imageBaseUrl.value}/uploads/activity/${url.replace(/^uploads[\/\\]activity[\/\\]/, '')}`;
    }
    const imageBaseUrl = ref(process.env.VUE_APP_IMAGE_BASE_URL || 'https://hm.yunxitech.cn');

    // 初始化
    onMounted(() => {
      fetchActivityList()
      fetchVenueList()
      fetchUserList()
      
      // 如果从场馆列表跳转过来，自动打开创建对话框
      if (route.params.venue_id || route.query.venue_id) {
        // 等待数据加载完成后打开对话框
        setTimeout(() => {
          showCreateDialog()
        }, 500)
      }
    })

    return {
      loading,
      submitLoading,
      dialogVisible,
      isEdit,
      selectedActivities,
      searchForm,
      pagination,
      activityList,
      venueList,
      userList,
      organizerList,
      form,
      rules,
      formRef,
      venueAvailable,
      venueAvailabilityMessage,
      currentVenueCapacity,
      uploadAction,
      uploadHeaders,
      route, // 添加 route 对象
      fetchActivityList,
      handleSearch,
      handleReset,
      showCreateDialog,
      openAddDialog: showCreateDialog,
      handleVenueChange,
      handleTimeChange,
      checkVenueAvailability,
      beforeImageUpload,
      handleImageSuccess,
      handleImageError,
      editActivity,
      handleSubmit,
      generateOrder,
      viewOrder,
      deleteActivity,
      viewDetail,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleDialogClose,
      getStatusType,
      getStatusText,
      getParticipantPercentage,
      formatDateTime,
      showDebugInfo,
      nodeEnv,
      uploadApiUrl,
      getOrderStatusType,
      getFullImageUrl,
      imageBaseUrl
    }
  }
}
</script>

<style scoped>
.activity-list {
  padding: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.page-header p {
  margin: 10px 0 0 0;
  color: #606266;
}

.search-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.time-info p {
  margin: 2px 0;
  font-size: 12px;
}

.participant-info {
  padding: 5px;
}

.order-status {
  text-align: center;
}

.order-amount {
  font-size: 12px;
  color: #409eff;
  font-weight: bold;
  margin-top: 4px;
}

.text-muted {
  color: #c0c4cc;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 图片上传样式 */
.activity-image-upload {
  display: flex;
  justify-content: center;
}

.activity-image-upload :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

.venue-tip {
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.upload-text {
  text-align: center;
  color: #606266;
}

.upload-text div:first-child {
  font-size: 14px;
  margin-bottom: 5px;
}

.upload-tip {
  font-size: 12px;
  color: #c0c4cc;
}

/* 场馆容量提示 */
.capacity-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
  
  .activity-image-upload :deep(.el-upload) {
    width: 150px;
    height: 100px;
  }
}
</style> 